package com.itheima.domain.store;

import com.itheima.service.store.QuestionService;
import com.itheima.service.store.impl.QuestionServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Program: heimamm
 * @Description:
 * @Author: choulan
 * @Date:2020-10-22 14:04
 **/
public class LoadData {
    static Map<String, Object> getTitles(Class<?> clazz) {
        List<Field> newFields = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f : declaredFields) {
            TdTitle annotation = f.getAnnotation(TdTitle.class);
            if (annotation == null) {
                continue;
            }
            newFields.add(f);
            titles.add(annotation.title());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("title", titles);
        map.put("field", newFields);
        return map;
    }


    public static void applySheet(Sheet sheet, List<?> list, int firstRow, int firstCol) {
        Map<String, Object> map = new HashMap<>();
        if (list != null && list.size() > 0) {
            map = getTitles(list.get(0).getClass());
        }
        List<Field> fields = (List<Field>) map.get("field");
        List<String> titles = (List<String>) map.get("title");
        Row row = sheet.createRow(firstRow);
        for (int i = 0; i < titles.size(); i++) {
            Cell cell = row.createCell(firstCol + i);
            cell.setCellValue(titles.get(i));
        }
        for (int i = 0; i < list.size(); i++) {
            Object item = list.get(i);
            Row row1 = sheet.createRow(firstRow  + 1 + i);
            for (int j = 0; j < fields.size(); j++) {
                Cell cell = row1.createCell(firstCol + j);
                try {
                    Field field = fields.get(j);
                    field.setAccessible(true);
                    Object val = field.get(item);//val=null
                    if(val!=null){
                        cell.setCellValue(val.toString());
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
